from typing import List, Dict

import requests
from flask import Flask, request, jsonify

app = Flask(__name__)

# API配置
API_URL = "https://api.siliconflow.cn/v1/chat/completions"
API_KEY = "sk-rnqurwrjarpxjetwkcphjymkcrbxpoyhpueaxwtkevmdwhlw"

# 模拟数据库存储用户聊天历史
user_chat_history: Dict[str, List[Dict[str, str]]] = {}


def get_ai_response(messages: List[Dict[str, str]]) -> str:
    """调用AI模型获取回复"""
    payload = {
        "model": "Qwen/QwQ-32B",
        "messages": messages
    }
    headers = {
        "Authorization": f"Bearer {API_KEY}",
        "Content-Type": "application/json"
    }

    try:
        response = requests.post(API_URL, json=payload, headers=headers)
        response.raise_for_status()
        return response.json()['choices'][0]['message']['content']
    except requests.exceptions.RequestException as e:
        return f"AI 模型调用失败: {str(e)}"


@app.route("/chat", methods=["POST"])
def chat():
    """处理用户聊天请求"""
    data = request.get_json()
    user_id = data.get("user_id")
    user_message = data.get("message")

    if not user_id or not user_message:
        return jsonify({"error": "缺少 user_id 或 message"}), 400

    # 初始化用户历史
    if user_id not in user_chat_history:
        user_chat_history[user_id] = []

    # 添加用户消息
    user_chat_history[user_id].append({"role": "user", "content": user_message})

    # 获取AI回复
    ai_response = get_ai_response(user_chat_history[user_id])

    # 添加AI回复到历史记录
    user_chat_history[user_id].append({"role": "assistant", "content": ai_response})

    return jsonify({
        "user_id": user_id,
        "response": ai_response,
        "chat_history": user_chat_history[user_id]
    })


@app.route("/history/<user_id>", methods=["GET"])
def get_history(user_id):
    """获取用户聊天历史"""
    history = user_chat_history.get(user_id, [])
    return jsonify(history)


@app.route("/history/<user_id>", methods=["DELETE"])
def clear_history(user_id):
    """清除用户聊天历史"""
    if user_id in user_chat_history:
        user_chat_history[user_id] = []
        return jsonify({"message": f"用户 {user_id} 的聊天历史已清除"})
    return jsonify({"message": f"用户 {user_id} 没有聊天历史"})


@app.route("/")
def index():
    return jsonify({"message": "Flask 聊天历史管理API正在运行", "endpoints": ["/chat", "/history/<user_id>"]})


if __name__ == "__main__":
    app.run(debug=True, host="0.0.0.0", port=8000)
